package com.iot08.api.service;

import com.alibaba.fastjson.JSONObject;
import com.iot08.api.config.redis.RedisClusterService;
import com.iot08.api.service.supplement.KafkaService;
import com.iot08.common.config.mongodb.query.UpdateVO;
import com.iot08.common.constant.ConstCacheField;
import com.iot08.common.constant.ConstKafka;
import com.iot08.common.entity.app.Device;
import com.iot08.common.entity.app.DeviceAppRecord;
import com.iot08.common.entity.app.PpChatGroup;
import com.iot08.common.utils.CollectionUtil;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author weichao 1299101858@qq.com
 * @version 1.0
 * @date 12/17/21 10:34 AM
 */
@Slf4j
@Service
public class DeviceResetAsyncService {

    @Resource
    private DeviceService deviceService;

    @Resource
    private DeviceMessageService deviceMessageService;
    @Resource
    private DeviceLocationService deviceLocationService;
    @Resource
    private DeviceLocationDailyService deviceLocationDailyService;
    @Resource
    private DevicePhotographService devicePhotographService;
    @Resource
    private DeviceStepDailyService deviceStepDailyService;

    @Resource
    private DeviceCostFlowService deviceCostFlowService;
    @Resource
    private DeviceDataFlowService deviceDataFlowService;
    @Resource
    private HeartRateRecordService heartRateRecordService;
    @Resource
    private HeartRateSettingService heartRateSettingService;
    @Resource
    private BloodPressureRecordService bloodPressureRecordService;

    @Resource
    private BloodPressureSettingService bloodPressureSettingService;
    @Resource
    private BloodOxygenRecordService bloodOxygenRecordService;
    @Resource
    private BloodOxygenSettingService bloodOxygenSettingService;
    @Resource
    private AnimalHeatRecordService animalHeatRecordService;
    @Resource
    private AnimalHeatSettingService animalHeatSettingService;

    @Resource
    private PpChatGroupService ppChatGroupService;
    @Resource
    private PpChatGroupMessageService ppChatGroupMessageService;

    @Resource
    private DeviceSedentaryService deviceSedentaryService;

    @Resource
    private DeviceCmsgService deviceCmsgService;

    @Resource
    private DeviceSanWordService deviceSanWordService;

    @Resource
    private DeviceAppRecordService deviceAppRecordService;

    @Resource
    private DevHCYAuthService devHCYAuthService;

    @Resource
    private KafkaService kafkaService;
    /**
     * 处理恢复出厂设置 的耗时操作
     * @param device
     * @param openid
     * @param type
     * @time: 12/16/21 6:45 PM
     * @author: Weichao
     * @version 1.0
     */
    @Async("resetDev_Task")
    public void handleResetDevEvents (Device device, String openid, String type){

        //cleanup relative data
        deviceMessageService.delByQuery(new Query(Criteria.where("i").is(device.getId())));
        deviceLocationService.delByQuery(new Query(Criteria.where("i").is(device.getId())));
        deviceLocationDailyService.delByQuery(new Query(Criteria.where("i").is(device.getId())));
        //删除远程拍照
        devicePhotographService.delByImei(device.getId());

        String watchCustomFunction = device.getWatchCustomFunction();
// 有一些需要根据 dev 的自动配置功能去进行 清除对应的数据,防止恢复出厂设置时 执行过多无效的数据库操作
        if(watchCustomFunction != null){
            if(watchCustomFunction.contains("P0")){
                //删除远程拍照
                devicePhotographService.delByImei(device.getId());
            }
            if(watchCustomFunction.contains("S0")){
                //删除计步的
                deviceStepDailyService.delByQuery(new Query(Criteria.where("i").is(device.getId())));
            }
            if(watchCustomFunction.contains("CF")){
                //查询话费流量
                deviceCostFlowService.delByQuery(new Query(Criteria.where("i").is(device.getId())));
            }
            if(watchCustomFunction.contains("DF")){
                //流量监控
                deviceDataFlowService.delById(device.getId());
            }
            //赛诺的是HR
            if(watchCustomFunction.contains("HR")){
//            if(watchCustomFunction.contains("H_HR")){
                // 心率
                heartRateRecordService.delByQuery(new Query(Criteria.where("i").is(device.getId())));
                heartRateSettingService.delById(device.getId());
            }
            if(watchCustomFunction.contains("H_BP")){
                // 血压
                bloodPressureRecordService.delByQuery(new Query(Criteria.where("i").is(device.getId())));
                bloodPressureSettingService.delById(device.getId());
            }
            if(watchCustomFunction.contains("H_BO")){
                // 血氧
                bloodOxygenRecordService.delByQuery(new Query(Criteria.where("i").is(device.getId())));
                bloodOxygenSettingService.delById(device.getId());
            }
            //赛诺的是TEMP
            if(watchCustomFunction.contains("TEMP")){
//            if(watchCustomFunction.contains("H_AH")){
                // 体温
                animalHeatRecordService.delByQuery(new Query(Criteria.where("i").is(device.getId())));
                animalHeatSettingService.delById(device.getId());
            }
            if(watchCustomFunction.contains("SR")){
                // 久坐提醒(Sedentary remind)
                deviceSedentaryService.delById(device.getId());
            }
            if(watchCustomFunction.contains("CMSG")){
                // 代收短信
                deviceCmsgService.delCmsgWithImei(device.getId());
            }

            if(watchCustomFunction.contains("PPMF")){
                //恢复出厂设置 需要碰碰交友的 好友都解绑了和删除聊天数据
                PpChatGroup ppChatGroup = ppChatGroupService.getByImei(device.getId());
                if (ppChatGroup != null) {
                    ppChatGroupMessageService.delByQuery(new Query(Criteria.where("i").is(ppChatGroup.getId())));
                    if (CollectionUtil.isNotEmpty(ppChatGroup.getMemberMap())) {
                        for (String key : ppChatGroup.getMemberMap().keySet()) {
                            PpChatGroup pcg = ppChatGroupService.getByImei(key);
                            if (pcg != null) {
                                CollectionUtil.removeMapKey(pcg.getMemberMap(), device.getId());
                                //删除更新
                                UpdateVO updateSub = new UpdateVO();
                                updateSub.setMap("m", pcg.getMemberMap());
                                ppChatGroupService.updateById(new ObjectId(pcg.getId()), updateSub);
//                                //下发同步好友 指令
//                                JSONObject json = new JSONObject();
//                                json.put("syncfriends", ppChatGroupService.getFriends(pcg));
//                                kafkaService.emitDeviceDemand(key, ConstKafka.DEVICE_TYPE_72, json);
                            }
                        }
                    }
                    ppChatGroupService.delById(new ObjectId(ppChatGroup.getId()));
                }
            }

            //生词本
            Integer updateWordCount = device.getUpdateWordCount();
            if(updateWordCount != null && updateWordCount > 0){
                //当生词本有记录时才清除  DICPEN
                deviceSanWordService.delByQuery(new Query(Criteria.where("i").is(device.getId())));
                UpdateVO update = new UpdateVO();
                update.set("updateWordCount", 0);
                deviceService.updateById(device.getId(),update);
            }
            //应用记录
            if(watchCustomFunction.contains("LMACHINE")){
                //要加索引 i , startTime
                deviceAppRecordService.delByQuery(new Query(Criteria.where("i").is(device.getId())));
            }

            if(watchCustomFunction.contains("YDYP")){
                // 和彩云
                devHCYAuthService.delById(device.getId());
            }
        }


        if (!"device".equals(type)) {
            JSONObject kafkaJson = new JSONObject();
            if (StringUtil.isNotBlank(openid)) {
                kafkaJson.put("openid", openid);
            }
            if ("web".equals(type)) {
                // web
                kafkaJson.put("operators", 1);
            }else{
                // app
                kafkaJson.put("operators", 0);
            }
            kafkaService.emitDeviceDemand(device.getId(), ConstKafka.DEVICE_TYPE_Reset, kafkaJson, openid);
        } else {
            //设备 自己恢复出厂设置
            //最后一次恢复出厂设置的时间
            RedisClusterService.getJedisCluster().hset(device.getId(), ConstCacheField.LAST_RESET_DATA_TIME, String.valueOf(System.currentTimeMillis() / 1000));
            RedisClusterService.getJedisCluster().hdel(device.getId(), ConstCacheField.TOKEN_TIME);
        }
        log.info("耗时操作处理完成:{}  操作者:{}, 恢复出厂设置类型:{}", device.getId(), openid, type);

    }
}
